package com.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.domain.po.Address;
import com.domain.po.User;
import com.domain.vo.AddressVO;
import com.domain.vo.UserVO;
import com.mapper.UserMapper;
import com.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {

    @Override
    public void deductBalance(Long id, Integer money) {
        //1 查询用户
        User user = getById(id);
        //2 判断用户状态
        if (user==null||user.getStatus()==2){
            throw new RuntimeException("用户状态异常！");
        }
        //3 检验余额是否充足
        if (user.getBalance()<money){
            throw new RuntimeException("用户余额不足！");
        }
        //扣减余额  update tb_user set balance = balance - ?
        baseMapper.deductBalance(id,money);
    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {
        //1 查询用户
        User user = getById(id);
        if (user==null||user.getStatus()==2){
            throw new RuntimeException("用户状态异常！");
        }
        //2 查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId,id).list();
        //3 封装VO
        //转User的PO为VO
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //转地址的VO
        if (CollUtil.isNotEmpty(addresses)){
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        //1 查询用户
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)){
            return Collections.emptyList();
        }
        //2查询地址
        //2.1 查询用户id集合
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        //2.2根据用户id查询地址
        List<AddressVO> addresses = Db.lambdaQuery(AddressVO.class).in(AddressVO::getId, userIds).list();
        //2.3转换地址VO
        List<AddressVO> addressVOList = BeanUtil.copyToList(addresses, AddressVO.class);
        //2.4用户地址集合分组处理，相同用户的放入一个集合中
        Map<Long,List<AddressVO>> addressMap = new HashMap<>(0);
        if (CollUtil.isNotEmpty(addressVOList)){
             addressMap = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }


        //3 转换VO返回
        List<UserVO> list = new ArrayList<>(users.size());
        for (User user : users) {
            //3.1转换User的PO为VO
            UserVO vo = BeanUtil.copyProperties(users, UserVO.class);
            list.add(vo);
            //3.2转换地址VO
            vo.setAddresses(addressMap.get(user.getId()));
        }
        return list;
    }
}
